#include "CConfig.h"
#include "CCFile.h"

#include <algorithm>

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/crc.hpp>

#include <fstream>
#include <sstream>



namespace ba = boost::archive;

CConfig::CConfig( bfs::path configPath):
		m_configPath(configPath)
{
	loadConfig();
}

CConfig::~CConfig(void)
{
}

void CConfig::addFile( CCFile * file )
{
	bfs::path  ccFilePath =  bfs::absolute(bfs::path( cacheDir() /= file->fileOutputPath() ));
	if( !bfs::exists( ccFilePath ))
	{
		try
		{
			bfs::create_directories( ccFilePath  );
		}
		catch ( std::exception& e )
		{
			std::cout << "Exception at creating dir" << file->fileOutputPath() << ":" << e.what();
		}
	}
}

bool CConfig::loadConfig()
{
	if( bfs::exists(m_configPath) )
	{		
		std::ifstream ifs( m_configPath.string().c_str() );
		ba::xml_iarchive ia(ifs);
		load(ia,1);
	}

	return true;
}

bool CConfig::saveConfig()
{
	if( bfs::exists(m_configPath) )
	{
		std::ofstream ofs;
		ofs.open(m_configPath.string().c_str(), std::ios::out | std::ios::in | std::ios::trunc );
		ba::xml_oarchive oa(ofs);
		save(oa,1);
	}
	else
	{	
		std::ofstream ofs;
		ofs.open(m_configPath.string().c_str(), std::ios::out | std::ios::in | std::ios::trunc );
		std::cout << "Is opened:" << ofs.is_open() << std::endl;

		try
		{
			ba::xml_oarchive oa(ofs);
			save(oa,1);
		}
		catch( std::exception& e)
		{
			std::cout << e.what() << std::endl;
		}

	}

	return true;
}

bool CConfig::isTracked( CCFile * inputFile )
{
	bfs::path  ccFilePath =  bfs::path( (cacheDir() /= inputFile->fileOutputPath()) /= std::string("obj.o") );
	bool tracked = bfs::exists( bfs::path(ccFilePath) );
	return tracked;
}
